<?php

class filelog
{
    /**
     * 创建文件
     *
     * @param $logpath
     * @throws Exception
     */
    public static function create($logpath)
    {
        if(!$logpath)
        {
            throw new Exception("file:{$logpath}} path error");
        }
        $dirpath = dirname($logpath);
        if(!file_exists($dirpath))
        {
            self::createDir($dirpath);
        }

        if(!file_exists($logpath))
        {
            $res = fopen($logpath, "w+");
            if($res === false)
            {
                throw new Exception("open file:{$logpath}} error");
            } else {
                fclose($res);
            }
        } else {
            file_put_contents($logpath, '');
        }
    }

    /**
     * 保存内容
     *
     * @param $message
     * @param $logpath
     * @param bool|true $append
     * @return bool
     * @throws Exception
     */
    public static function save($message, $logpath, $append = true)
    {
        if(!file_exists($logpath))
        {
            self::create($logpath);
        }

        $message && $message .= PHP_EOL;
        if($append)
        {
            file_put_contents($logpath, $message, FILE_APPEND);
        } else {
            file_put_contents($logpath, $message);
        }
    }

    /**
     * 创建目录
     *
     * @param $dirpath
     * @return bool
     */
    public static function createDir($dirpath)
    {
        if(!file_exists($dirpath))
        {
            $arr = explode('/', str_replace("\\", "/", $dirpath));
            $build = '';
            foreach($arr as $dir)
            {
                if('' === $dir)
                {
                    continue;
                }
                if(strstr($dir, ":") != false)
                {
                    $build = $dir;
                    continue;
                }
                $build .= "/$dir";
                if(!is_dir($build))
                {
                    if(!mkdir($build, 0777))
                    {
                        throw new Exception("mkdir:{$build} error");
                    }
                    chmod($build, 0777);
                }
            }
        }

        return true;
    }

    /**
     * 一行一行读取所有内容，以数组方式返回
     * @param $filepath
     * @return array
     */
    public static function readAll($filepath)
    {
        $content = array();
        if(!file_exists($filepath))
        {
            return $content;
        }
        $handle = fopen($filepath, 'r');
        if(!is_resource($handle))
        {
            return $content;
        }

        while (!feof($handle))
        {
            $line = trim(fgets($handle));
            $line && $content[] = $line;
        }
        fclose($handle);

        return $content;
    }
}